package cn.easy.rest.controller;

import cn.easy.api.SensorService;
import cn.easy.common.pojo.EasyResult;
import cn.easy.common.pojo.SensorType;
import cn.easy.common.util.ExceptionUtil;
import cn.easy.pojo.Sensor;
import cn.easy.pojo.User;
import cn.easy.rest.dao.JedisClient;
import cn.easy.rest.util.UserKeyUtil;
import cn.easy.vo.SensorVo;
import cn.easy.vo.SwitchVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/sensor")
@Controller
/**
 * 传感器控制层
 * @author 谢子豪
 * @time 2017/10/6
 * @description
 */
public class SensorController {
    @Reference
    private SensorService sensorService;
    @Autowired
    private JedisClient jedisClient;

    /**
     * 新增一个传感器
     *
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/insertSensor", method = RequestMethod.POST)
    public EasyResult insertSensor(@RequestBody Map map, HttpServletRequest request) {
        String userKey = UserKeyUtil.getUserInfoFromToken(request, jedisClient);
        int deviceId;
        /*---------查看必要的参数-----------*/
        if (!map.containsKey("deviceId")) return EasyResult.fail("缺少设备id");
        else deviceId = Integer.parseInt(map.get("deviceId").toString());
        Sensor sensor = new Sensor();
        if (!map.containsKey("sensorName")) return EasyResult.fail("缺少传感器名称");
        else sensor.setSensorName(map.get("sensorName").toString());
        if (!map.containsKey("sensorType")) return EasyResult.fail("缺少传感器类型");
        else {
            int sensorType = Integer.parseInt(map.get("sensorType").toString());
            //判断传感器是不是已知类型
            if (checkSensorType(sensorType)) return EasyResult.fail("未知的传感器类型");
            //设置传感器类型
            sensor.setSensorType(sensorType);

        }
        /*----------新增传感器------------*/
        try {
            sensorService.insertSensor(userKey, deviceId, sensor);
            //新增传感器是开关的时候，要设置jedis
            return EasyResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }

    }

    /**
     * 删除一个传感器
     *
     * @param sensorId
     * @param userKey
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteSensor/{sensorId}/{userKey}", method = RequestMethod.GET)
    public EasyResult deleteSensor(@PathVariable int sensorId, @PathVariable String userKey) {
        try {
            sensorService.deleteSensor(userKey, sensorId);
            return EasyResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }
    }

    /**
     * 更新传感器
     *
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateSensor", method = RequestMethod.POST)
    public EasyResult updateSensor(@RequestBody Map map, HttpServletRequest request) {
        Sensor sensor = new Sensor();
        String userKey = UserKeyUtil.getUserInfoFromToken(request, jedisClient);
        /*-------检查必要参数-------*/
        if (!map.containsKey("sensorId")) return EasyResult.fail("缺少传感器编号");
        else sensor.setSensorId(Integer.parseInt(map.get("sensorId").toString()));
        /*--------赋值-----------*/
        if (map.containsKey("sensorName")) sensor.setSensorName(map.get("sensorName").toString());
        if (map.containsKey("sensorState")) sensor.setSensorState(Integer.parseInt(map.get("sensorState").toString()));

        /*--------存入数据库--------------*/
        try {
            sensorService.updateSensor(userKey, sensor);
            return EasyResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }

    }

    /**
     * 获取设备下所有的传感器，前提是设备必须是公开的
     *
     * @param deviceId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchDevicePublicSensor/{deviceId}", method = RequestMethod.GET)
    public EasyResult searchDevicePublicSensor(@PathVariable int deviceId) {
        try {
            List<Sensor> list = sensorService.searchDevicePublicSensor(deviceId);
            return EasyResult.build(200, "success", list);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = e.getMessage();
            return EasyResult.build(500, msg);
        }

    }

    /**
     * 获取设备下所有的传感器，不管公不公开
     *
     * @param deviceId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchDeviceAllSensor/{deviceId}", method = RequestMethod.GET)
    public EasyResult searchDeviceAllSensor(@PathVariable int deviceId, HttpServletRequest request) {
        String userKey = UserKeyUtil.getUserInfoFromToken(request, jedisClient);
        try {
            List<Sensor> sensorList = sensorService.searchDeviceAllSensor(deviceId, userKey);
            return EasyResult.ok(sensorList);

        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }

    }

    /**
     * 获取开关状态
     *
     * @return
     */
    @RequestMapping(value = "/getSwitchState/{sensorId}", method = RequestMethod.GET)
    @ResponseBody
    public EasyResult getSwitchState(@PathVariable Integer sensorId, HttpServletRequest request) {
        SensorVo sensorVo = null;
        ObjectMapper objectMapper = new ObjectMapper();
        // 获取用户的key
        String userKey = UserKeyUtil.getUserInfoFromToken(request, jedisClient);

        //从redis中获取
        String data = jedisClient.get("EASY_SWITCH_" + sensorId + "");
        //找不到从数据库获取
        if (data == null) {
            System.out.println("从数据库中取出数据");
            try {
                SwitchVo switchVo = sensorService.getSwitchState(sensorId, userKey);
                jedisClient.set("EASY_SWITCH_" + sensorId.toString(), objectMapper.writeValueAsString(switchVo));
                return EasyResult.ok(switchVo.getState());
            } catch (Exception e) {
                e.printStackTrace();
                return EasyResult.fail(e.getMessage());
            }
        } else {
            System.out.println("直接走缓存");
            try {
                SwitchVo switchVo = objectMapper.readValue(data, SwitchVo.class);
                if (!switchVo.getUserKey().equals(userKey)) return EasyResult.fail("身份验证失败");
                return EasyResult.ok(switchVo.getState());
            } catch (IOException e) {
                e.printStackTrace();
                return EasyResult.fail("json转对象失败");
            }
        }

    }

    /**
     * 查询 传感器的详细信息，如果传感器所属的设备是非公开的，会验证userKey
     *
     * @param request
     * @param sensorId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSensorInfo/{sensorId}", method = RequestMethod.GET)
    public EasyResult getSensorInfo(HttpServletRequest request, @PathVariable Integer sensorId) {
        String userKey = UserKeyUtil.getUserInfoFromToken(request, jedisClient);
        try {
            Sensor sensor = sensorService.searchSensorById(sensorId, userKey);
            return EasyResult.ok(sensor);
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }
    }

    /**
     * 判断传感器的种类是不是允许的传感器
     *
     * @param sensorType
     * @return
     */
    public static boolean checkSensorType(int sensorType) {
        boolean flag = true;
        for (SensorType type : SensorType.values()) {
            if (sensorType == type.getIndex()) flag = false;
        }
        return flag;
    }


}
